package com.platform.api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.platform.annotation.IgnoreAuth;
import com.platform.entity.MpMsgEntity;
import com.platform.entity.ShortUrlEntity;
import com.platform.service.MpMsgService;
import com.platform.service.ShortUrlService;
import com.platform.util.ApiBaseAction;
import com.platform.utils.R;
import com.platform.utils.RRException;

import io.swagger.annotations.Api;
import jodd.util.StringUtil;

@Api(tags = "API短域名相关接口")
@RestController
@RequestMapping("/api/shorturl")
public class ApiShortUrlController extends ApiBaseAction {

    private Logger logger = Logger.getLogger(getClass());
    
    @Autowired
    private ShortUrlService shortUrlService;
    @Autowired
    private MpMsgService mpMsgService;
	
    @IgnoreAuth
    @RequestMapping("/{mpId}/{surl}")
    public R redirect(@PathVariable("mpId") Integer mpId,
    		@PathVariable("surl") String surl,
    		HttpServletRequest request, HttpServletResponse response) {
        try {
            Integer referenceId = null;
            if(request.getParameter("referenceId") != null) {
            	try {
    				referenceId = Integer.valueOf(request.getParameter("referenceId"));
    			} catch (NumberFormatException e) {
    				referenceId = 0;
    			}
            }else {
				referenceId = 0;
            }
            
            ShortUrlEntity shortUrl = shortUrlService.getByKey(mpId + "_" + surl);
            MpMsgEntity mpMsg = mpMsgService.queryObject(mpId);
            String realUrl = mpMsg.getHomeUrl() + shortUrl.getRealUrl() + "?referenceId="+referenceId;
            if(StringUtil.isNotBlank(request.getParameter("id"))) {
            	realUrl = realUrl + "&id=" + request.getParameter("id");
            }
            if(StringUtil.isNotBlank(request.getParameter("from"))) {
            	realUrl = realUrl + "&from=" + request.getParameter("from");
            }
        	response.sendRedirect(realUrl);
			return null;
        }catch(RRException e) {
        	logger.error(e.getMessage(),e);
        	return R.error(500, e.getMessage());
        } catch (Exception e) {
        	logger.error(e.getMessage(),e);
        	logger.error("微信ApiShortUrlController redirect error:"+e.getMessage());
        	return R.error(500, e.getMessage());
        }
    }
	
}
